<?php
/**
 * 刮刮乐基础傻瓜版
 *
 * BY:拥抱&&k7gxn56
 * 
 * QQ572300808 && 799590989
 */
defined('IN_IA') or exit('Access Denied');

class YyyModule extends WeModule {
	public $name = 'YyyModule';
	public $title = '摇一摇';
	public $ability = '';
	public $table_reply = 'yyy_reply';//一条规则
	public $table_award = 'yyy_award';//奖品
	public $table_winner = 'yyy_winner';
	public function fieldsFormDisplay($rid = 0) {
		global $_W;
		if (!empty($rid)) {
			
			$reply = pdo_fetch("SELECT * FROM ".tablename($this->table_reply)." WHERE rid = :rid ORDER BY `id` DESC", array(':rid' => $rid));
			if($reply['start_time']){
				$reply['start_time'] = date('Y-m-d H:i:s',$reply['start_time']);
			}
			if($reply['end_time']){
				$reply['end_time'] = date('Y-m-d H:i:s',$reply['end_time']);
			}
		} else {
			$reply = array(
				'maxlottery' => 1,
				'start_time' => '',
				'end_time'	 => ''
			);
		}
		include $this->template('yyy/form');
	}

	public function fieldsFormValidate($rid = 0) {
		return true;
	}

	public function fieldsFormSubmit($rid = 0) {
		global $_GPC, $_W;
		$id = intval($_GPC['reply_id']);
		$insert = array(
			'rid' => $rid,
            'title' => $_GPC['title'],
			'picture' => $_GPC['picture'],
			'end_picture' => $_GPC['picture_end'],
			'description' => $_GPC['description'],
			'maxlottery' => intval($_GPC['maxlottery']),
			'countdown' => $_GPC['countdown'],
			'weid'		=> $_W['account']['weid'],
			'rule' => $_GPC['rule'],
			'check' => $_GPC['check'],
			'start_time' => strtotime($_GPC['start_time']),
			'runstatus' => 'dd',
			'end_time' => strtotime($_GPC['end_time'])
		);
		if (empty($id)) {
			pdo_insert($this->table_reply, $insert);
		} else {
			if (!empty($_GPC['picture'])) {
				file_delete($_GPC['picture-old']);
			} else {
				unset($insert['picture']);
			}
			if(!empty($_GPC['picture_end'])){
				file_delete($_GPC['picture2-old']);
			}else{
				unset($insert['end_picture']);
			}
			pdo_update($this->table_reply, $insert, array('id' => $id));
		}
	}

	public function ruleDeleted($rid = 0) {
		global $_W;
		$replies = pdo_fetchall("SELECT id, thumb FROM ".tablename($this->table_reply)." WHERE rid = '$rid'");
		$deleteid = array();
		if (!empty($replies)) {
			foreach ($replies as $index => $row) {
				file_delete($row['thumb']);
				$deleteid[] = $row['id'];
			}
		}
		pdo_delete($this->table_reply, "id IN ('".implode("','", $deleteid)."')");
		return true;
	}

	public function doFormDisplay(){
		global $_W, $_GPC;
		$result = array('error' => 0, 'message' => '', 'content' => '');
		$result['content']['id'] = $GLOBALS['id'] = 'add-row-news-'.$_W['timestamp'];
		$result['content']['html'] = $this->template('yyy/item', TEMPLATE_FETCH);
		exit(json_encode($result));
	}

	public function doyyy($rid = 0) {
		global $_GPC ,$_W;
		$title = '摇一摇';
		$fromuser = authcode(base64_decode($_GPC['from_user']), 'DECODE');
		//select b.weid from ims_lotery_reply as a left join ims_rule  as b on a.rid = b.id where 1;
		//查询weid为后面跳转做铺垫
        $we = pdo_fetch("select b.weid from ims_yyy_reply as a left join ims_rule  as b on a.rid = b.id where 1");
		$id = intval($_GPC['id']);
        $member = pdo_fetch("SELECT * FROM ".tablename('fans')." WHERE from_user = '{$fromuser}' AND `weid`='{$we['weid']}'");
		$yyy = pdo_fetch("SELECT * FROM ".tablename($this->table_reply)." WHERE rid = '".$id."' LIMIT 1");
		//$total = pdo_fetchcolumn("SELECT count(*) FROM ".tablename($this->table_winner)." WHERE weid={$we['weid']} AND rid = '{$id}' AND from_user='{$fromuser}'");
		if (empty($yyy)) {
			exit('非法参数！0');
		}
		//$data = pdo_fetchall("SELECT a.nickname, a.qq, a.from_user, a.realname, b.from_user, b.aid, b.`status`, b.award, c.id, c.`level`, c.rid, b.rid, a.mobile, a.sex, a.age, a.jifen, b.createtime FROM ims_fans AS a , ims_ggl_winner AS b , ims_ggl_award AS c WHERE a.from_user = b.from_user AND b.aid = c.id AND b.rid = c.rid ORDER BY b.id DESC");
		//强行会员登记
		if (empty($member['realname'])) {
				$from_user = authcode(base64_decode($_GPC['from_user']), 'DECODE');
				$user = pdo_fetch("SELECT * FROM ".tablename('fans')." WHERE from_user = '".$from_user."' and weid=".$we['weid']." limit 1");		      
		      if($_GPC['action']=='setinfo'){
		     		$insert = array(
					'nickname' => $_GPC['nickname'],
					'realname' => $_GPC['realname'],
					'mobile' => $_GPC['mobile'],
					'qq' => $_GPC['qq'],
		          	'sex' => $_GPC['sex'],
					'age' => $_GPC['age'],          
					'from_user'=>$from_user,
		          		'weid'=>$we['weid'],
		          		'createtime'=>time(),
				);
		     		$insert_winner = array(
		     				'rid' => $id,
		     				'playnum' => '1',
		     				'from_user' => $from_user,
		     				'status' => 1,
		     				'weid' => $we['weid'],
		     				'createtime' =>time()
		     		);
		     	
			    if ($user==false) {
					$id=pdo_insert('fans', $insert);
					$result = pdo_insert($this->table_winner,$insert_winner);
					
				} else {
					pdo_update('fans', $insert, array('from_user' => $from_user,'weid'=>$we['weid']));
				}
				die(true);
		      }
			$title = '会员资料';	
			$loclurl=create_url('index/module', array('do' => 'yyy', 'name' => 'yyy', 'id' => $id,'weid'=> $we['weid'], 'from_user' => $_GPC['from_user']));
			$loclurl_1=create_url('index/module', array('do' => 'yyy', 'name' => 'yyy', 'id' => $id, 'from_user' => $_GPC['from_user']));
			include $this->template('yyy/register');
		} else {
			$now = time();
			if ($yyy['status'] && ($now >= $yyy['start_time'] && $now <= $yyy['end_time'])) {
				include $this->template('yyy/yyy');
			} else {
				message('活动已结束!更多活动请关注官方微信！', create_url('index/module', array('do' => 'yyy', 'name' => 'yyy', 'id' => $id, 'from_user' => $_GPC['from_user'])));
				include $this->template('yyy/yyy');
			}
		}
	}
	public function doGetaward() {
		global $_GPC, $_W;
		$fromuser = authcode(base64_decode($_GPC['from_user']), 'DECODE');
		if (empty($fromuser)) {
			exit('非法参数1！');
		}
		
		$id = intval($_GPC['id']);//模块ID
		$rand_gifts=$this->doGetPnum();
		$rand_gifts=json_decode($rand_gifts);
        
        $insert_winner = array(
			'rid' => $id,
			'playnum' => $_GPC['playnum'],
			'from_user' => $rand_gifts->from_user,
			'status' => 1,
			'weid' => $rand_gifts->weid,
			'createtime' =>time()
		);

		if (!empty($rand_gifts)) {
		    $result = pdo_update($this->table_winner,$insert_winner,array('id' => $rand_gifts->id));
			//print_r($result);
		}else{
		    $result = pdo_insert($this->table_winner,$insert_winner);
			//print_r($result);
		}

	}
	
	public function doGetStatus(){
	    global $_GPC, $_W;
		$fromuser = authcode(base64_decode($_GPC['from_user']), 'DECODE');
		if (empty($fromuser)) {
			exit('非法参数3！');
		}
		return $this->doGetStatu();
	}
	public function doGetPnum(){
		global $_GPC, $_W;
		$fromuser = authcode(base64_decode($_GPC['from_user']), 'DECODE');
		if (empty($fromuser)) {
			exit('非法参数1！');
		}
		
		$id = intval($_GPC['id']);//模块ID
		$egg = pdo_fetch("SELECT * FROM ".tablename($this->table_reply)." WHERE rid = '$id' LIMIT 1");
		if (empty($egg)) {
			exit('抽奖活动还未开始!');
		}
		$weid = $egg['weid'];//当前的公众号ID
		$rand_gifts = pdo_fetch("SELECT * FROM ".tablename($this->table_winner)." WHERE weid={$weid} AND rid = {$id} AND from_user='{$fromuser}'");
		if(empty($rand_gifts)){
			$insert_winner = array(
					'rid' => $id,
					'playnum' => '1',
					'from_user' => $fromuser,
					'status' => 1,
					'weid' => $weid,
					'createtime' =>time()
			);
			$result = pdo_insert($this->table_winner,$insert_winner);
			$rand_gifts = pdo_fetch("SELECT * FROM ".tablename($this->table_winner)." WHERE weid={$weid} AND rid = {$id} AND from_user='{$fromuser}'");
				
		}
		return json_encode($rand_gifts);
	}
	
	public function doGetStatu(){
	    global $_GPC, $_W;
		$id = intval($_GPC['id']);//模块ID
		$egg = pdo_fetch("SELECT * FROM ".tablename($this->table_reply)." WHERE rid = '$id' LIMIT 1");
		if (empty($egg)) {
			exit('抽奖活动还未开始!');
		}
        $weid = $egg['weid'];//当前的公众号ID
		$egg = pdo_fetch("SELECT runstatus FROM ".tablename($this->table_reply)." WHERE weid = ".$weid.' AND rid = '.$id);
		return $egg['runstatus'];
	}
	public function doShowtime(){
	    global $_GPC, $_W;
		$id = intval($_GPC['id']);//模块ID
	    include $this->template('yyy/show');
	}
	
	public function doAwardlist() {
		global $_GPC, $_W;
		checklogin();
		$weid = $_W['account']['weid'];//当前公众号ID
		$id = intval($_GPC['id']);
		if (checksubmit('delete')) {
			pdo_delete($this->table_winner, " id IN ('".implode("','", $_GPC['select'])."')");
			message('删除成功！', create_url('index/module', array('do' => 'awardlist', 'name' => 'yyy', 'id' => $id, 'page' => $_GPC['page'])));
		}
		//取得获奖列表
		$list_award = pdo_fetchall("SELECT W.playnum,F.nickname FROM ims_yyy_winner AS W LEFT JOIN ims_fans AS F ON W.from_user=F.from_user WHERE W.weid=$weid AND W.rid=$id ORDER BY W.playnum DESC");
		
		//SELECT W.*,F.* FROM ims_ggl_winner AS W LEFT JOIN ims_fans AS F ON W.from_user=F.from_user WHERE W.weid=$weid AND W.rid=$id ORDER BY W.playnum ASC
		
		
		echo json_encode($list_award);
		//return $list_award;
		//include $this->template('ggl/awardlist');
	}

	
	public function dolist() {
		global $_GPC, $_W;
		checklogin();
		$weid = $_W['account']['weid'];//当前公众号ID
		$id = intval($_GPC['id']);
		if (checksubmit('delete')) {
			pdo_delete($this->table_winner, " id IN ('".implode("','", $_GPC['select'])."')");
			message('删除成功！', create_url('index/module', array('do' => 'awardlist', 'name' => 'yyy', 'id' => $id, 'page' => $_GPC['page'])));
		}
		//取得获奖列表
		$list_award = pdo_fetchall("SELECT W.playnum,F.nickname,W.createtime FROM ims_yyy_winner AS W LEFT JOIN ims_fans AS F ON W.from_user=F.from_user WHERE W.weid=$weid AND W.rid=$id ORDER BY W.playnum DESC");
	
		//SELECT W.*,F.* FROM ims_ggl_winner AS W LEFT JOIN ims_fans AS F ON W.from_user=F.from_user WHERE W.weid=$weid AND W.rid=$id ORDER BY W.playnum ASC

		//echo json_encode($list_award);
		//return $list_award;
		include $this->template('yyy/awardlist');
	}
	
	
	
	public function doDelete() {
		global $_W,$_GPC;
		$id = intval($_GPC['id']);
		$rid = intval($_GPC['rid']);
		$sql = "SELECT id FROM " . tablename($this->table_award) . " ";
		$row = pdo_fetch($sql, array(':id'=>$id));
		
		if (empty($row)) {
			message('抱歉，奖品不存在或是已经被删除！', '', 'error');
		}
		if (!pdo_delete($this->table_award, array('id' => $id))){
			$url = create_url('rule/post', array('id' => $rid));
			message('删除奖品成功', $url, 'success'); 
		}
	}
	
	public function dostatus( $rid = 0) {
		global $_GPC;
		$rid = $_GPC['rid'];
		echo $rid;
		$insert = array(
			'status' => $_GPC['status']
		);
		
		pdo_update($this->table_reply,$insert,array('rid' => $rid));
		message('模块操作成功！', referer(), 'success');
	}	
	
	public function doRunstatus($status='fin') {
		global $_GPC;
		$rid = $_GPC['id'];
		if($_GPC['runstatus']!=''){
		    $status=$_GPC['runstatus'];
		}
		$insert = array(
			'runstatus' => $status
		);
		pdo_update($this->table_reply,$insert,array('rid' => $rid));
		//message('模块操作成功！', referer(), 'success');
	}	

}
